import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:znmm/UI/LoginPages/mag/user_info_manage.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/network/api_url.dart';
import 'package:znmm/network/dio_https.dart';

import '../model/cn_user_model.dart';

class CnUserMag {
  static final CnUserMag _singleton = CnUserMag._internal();
  factory CnUserMag() {
    return _singleton;
  }

  CnUserMag._internal();

  CnUserModel _pmodel = CnUserModel();
  CnUserModel getCnUserModel() => _pmodel;

  bool _bHaveData = false;

  void clean() {
    _bHaveData = false;
  }

  void doSomething() {
    print("Doing something...");
  }

  void reqUserInfo({void Function()? callback}) {
    if (_bHaveData || UserInfoMag().bIsVisito) return;
    String userIdStr = UserInfoMag().user_id;
    String urlStr =
        "/wp-json/wc/v3/customers/$userIdStr/?consumer_key=$consumer_key&consumer_secret=$consumer_secret";

    DioHttps dioUtil = DioHttps.instance!;
    dioUtil
        .request<dynamic>(
      urlStr,
      //bIsShowLoading: false,
      //bIsShowResponse: true,
      method: DioMethod.get,
    )
        .then((response) {
      // 处理响应数据
      if (response == null) return;
      print("response:$response");
      _bHaveData = true;
      _pmodel = CnUserModel.fromJson(response);
    });
  }

  //
  void editUserinfo(
      {required String firstName,
      required String lastName,
      required String email,
      void Function()? callback}) {
    if (email.isEmpty || !MyGlobal.isValidEmail(email)) {
      SmartDialog.showToast("Incorrect email format");
      return;
    }

    String userIdStr = UserInfoMag().user_id;
    String urlStr =
        "/wp-json/wc/v3/customers/$userIdStr/?consumer_key=$consumer_key&consumer_secret=$consumer_secret";

    DioHttps dioUtil = DioHttps.instance!;
    dioUtil
        .request<dynamic>(
      urlStr,
      data: {"first_name": firstName, "last_name": lastName, "email": email},
      //bIsShowLoading: false,
      //bIsShowResponse: true,
      method: DioMethod.put,
    )
        .then((response) {
      // 处理响应数据
      if (response == null) return;
      print("response:$response");

      _pmodel = CnUserModel.fromJson(response);

      if (callback != null) {
        callback();
      }
    });
  }

  //billing编辑
  void billingEdit(
      String strType, List<String> selKeyList, List<String> selValueList,
      {void Function()? callback}) {
    if (selKeyList.length != selValueList.length || selValueList.length < 2) {
      SmartDialog.showToast(" key and value mismatch !!!");
      return;
    }

    // 判断是否为空
    // bool containsEmpty = selValueList.any((element) => element.isEmpty);
    // if (containsEmpty ) {
    //   // 1.请填写基本信息表单(账单地址)
    //   SmartDialog.showToast("Please fill in the blank form");
    //   return;
    // }

    String emailStr = selValueList[selValueList.length - 2];

    if (strType == "billing" &&
        (emailStr.isEmpty || !MyGlobal.isValidEmail(emailStr))) {
      SmartDialog.showToast("Incorrect email format");
      return;
    }

    Map<String, String> combinedMap =
        Map.fromIterables(selKeyList, selValueList);

    String userIdStr = UserInfoMag().user_id;
    String strUrl =
        "/wp-json/wc/v3/customers/$userIdStr/?consumer_key=$consumer_key&consumer_secret=$consumer_secret";

    DioHttps dioUtil = DioHttps.instance!;
    dioUtil
        .request<dynamic>(
      strUrl,
      data: {strType: combinedMap}, //billing  shipping
      //bIsShowLoading: false,
      //bIsShowResponse: true,
      method: DioMethod.put,
    )
        .then((response) {
      // 处理响应数据
      if (response == null) return;
      print("response:$response");

      _pmodel = CnUserModel.fromJson(response);

      if (callback != null) {
        callback();
      }
    });
  }

  // 获取订单详情
  // Future<void> getOrderInfo({required int userId}) async {
  //   // 先清空
  //   UserinfoService().to.dataRowList = [];
  //   UserinfoService().to.orderInfoList = [];

  //   var res = await DioHttps().request(
  //       "/wp-json/wc/v3/orders/?consumer_key=$consumer_key&consumer_secret=$consumer_secret",
  //       //baseUrlIndex: 1,
  //       method: PTDioMethod.get,
  //       bIsShowResponse: true,
  //       params: {"page": UserinfoService().to.currentPageIndex, "per_page": 3});
  //   // 1.如果订单小于3或者等于0，说明没有下一页了
  //   if (List.castFrom(res).length < 3) {
  //     UserinfoService().to.isHaveNextPage = false;
  //     // 空的
  //     if (List.castFrom(res).isEmpty) {
  //       return;
  //     }
  //     // 遍布最后的
  //     for (int i = 0; i < List.castFrom(res).length; i++) {
  //       UserinfoService().to.orderInfoList.add(res[i]); // 保存订单数据
  //       OrderInfoModel orderInfoModel = OrderInfoModel.fromJson(res[i]); // 实体类
  //       // 3.循环遍历放进封装的组件
  //       UserinfoService().to.dataRowList.add(_orderWidget(
  //           orderId: "${orderInfoModel.id}",
  //           orderStatus: orderInfoModel.status!,
  //           orderTotal:
  //               "${orderInfoModel.currencySymbol}${orderInfoModel.total}",
  //           currentIndex: i));
  //     }
  //     return;
  //   } else {
  //     UserinfoService().to.isHaveNextPage = true;
  //     // 2.每次获取3个
  //     for (int i = 0; i < 3; i++) {
  //       UserinfoService().to.orderInfoList.add(res[i]); // 保存订单数据
  //       OrderInfoModel orderInfoModel = OrderInfoModel.fromJson(res[i]); // 实体类
  //       // 3.循环遍历放进封装的组件
  //       UserinfoService().to.dataRowList.add(_orderWidget(
  //           orderId: "${orderInfoModel.id}",
  //           orderStatus: orderInfoModel.status!,
  //           orderTotal:
  //               "${orderInfoModel.currencySymbol}${orderInfoModel.total}",
  //           currentIndex: i));
  //     }
  //   }
  // }
}
